import Vue from 'vue'
import axios from 'axios'
import qs from 'qs';
import { Toast } from 'vant';
import VueCookies from 'vue-cookies'
Vue.use(VueCookies);
import md5 from 'js-md5'


const http = axios.create({
  // retry: 0,
  // timeout: 1000 * 30,
  // withCredentials: true,
  // headers: {
  //   'Content-Type': 'application/json; charset=utf-8'
  // }
  // baseURL: "http://testcx.fescorock.com"
  // baseURL: "http://47.95.203.71:3000/mock/37",
  // baseURL: process.env.VUE_APP_ip,
  // baseURL: "",


})

http.interceptors.request.use(
  config => {
    // let userOpenid = window.localStorage.getItem('userOpenid')
    // let userToken = window.localStorage.getItem('userToken')
    // if (userOpenid) {
    //   config.headers.openid = `${userOpenid}`;
    //   config.headers.wxtoken = `${userToken}`;
    // }
    // let obj = Object.assign({
    //   appaccount: 'NetworkApp',
    //   noncestr: '041da15f-a5cf-44a9-bf24-4243736a60d6',
    //   timestamp: Math.round(new Date().getTime() / 1000).toString(),
    // }, config.params);
    // let str = 'dc79116859df79db9c7c77ed923a3703';
    // Object.keys(obj).sort((a, b) => {
    //   return a[0].toLowerCase() > b[0].toLowerCase() ? 1 : a[0].toLowerCase() === b[0].toLowerCase() ? 0 : -1
    // }).forEach(val => {
    //   str += val + obj[val]
    // });
    // config.params = {
    //   sign: md5(str),
    //   appaccount: 'NetworkApp',
    //   noncestr: '041da15f-a5cf-44a9-bf24-4243736a60d6',
    //   timestamp: obj.timestamp,
    //   jsonParam: JSON.stringify(config.params)
    // };

    if (config.url.indexOf('/openapi/helo/token') == -1) {
      config.headers['Authorization'] = Vue.$cookies.get('Authorization') // 请求头带上token 
    }
    if (config.isLoading !== false) { // 如果配置了isLoading: false，则不显示loading

    }
    return config;
  },
  error => {

    return Promise.reject(error.response);
  });

http.interceptors.response.use(
  response => {  //成功请求到数据  
    console.log(response.data, 'response.data')
    const res = response.data
    if (res instanceof ArrayBuffer) {
      if (response.status === 200) {
        return response.data
      } else {
        Toast(response.data.message);
        return Promise.reject(response);
      }
    } else {
      if (response.data.status === 200) {
        return response.data
      } else {
        Toast(response.data.message);
        return Promise.reject(response);
      }
    }

  },
  error => {  //响应错误处理     
    let text = ''
    text = error.response.data.message
    Toast(text);
    return Promise.reject(error)
  })

http.$data = (data = {}, contentType = 'json') => {
  // var defaults = {
  // 't': new Date().getTime()
  // }
  // data = merge(defaults, data)
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}




Vue.prototype.$http = http

// Vue.prototype.baseUrl = " http://testcx.fescorock.com/"


